<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    省
    <select name="" id="pro">
        <option value="">请选择</option>
    </select>

    市
    <select name="" id="city">
        <option value="">请选择</option>
    </select>


    <script>


        // 请选择  value = ""   省份相当于没选

        //   省份onchange 的时候  要判断 this.value  

        //   filter 







        const oPro = document.querySelector('#pro') ;

        const oCity = document.querySelector('#city') ;


        const xhr = new XMLHttpRequest();

        xhr.open('get', '../data/city.json', true);

        xhr.send();

        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                let data = xhr.responseText;
                // console.log(data);
                data = JSON.parse(data);
                console.log(data);

                // 显示省份
                let proHTML = '<option value="">请选择</option>' ;
                data.forEach( v => {
                    const { province } = v ;
                    proHTML += `<option value="${province}">${province}</option>` ;
                })
                oPro.innerHTML = proHTML ;

                // 省份选择以后  --- 失去焦点且发生改变
                oPro.onchange = function() {
                    // 获取省份
                    const proVal = this.value ;
                    console.log(proVal);

                    // 是否点了省份   可能点了请选择选择
                    if(proVal) {
                        // 通过省份得到市
                        const cityArr = data.filter( v => v.province === proVal)[0].children ;
                        console.log(cityArr);

                        let cityHTML = '<option value="">请选择</option>' ;
                        cityArr.forEach( v => {
                            cityHTML += `<option value="${v}">${v}</option>` ;
                        })

                        // console.log(cityHTML);

                        oCity.innerHTML = cityHTML ;
                    } else {
                        oCity.innerHTML = '<option value="">请选择</option>' ;
                    }
                } 

            }
        }

    </script>

</body>

</html>